package com.csc.banking.dao;

import java.util.Date;

import javax.persistence.EntityManager;
import javax.persistence.PersistenceContext;
import javax.persistence.Query;
import javax.persistence.TypedQuery;

import org.springframework.stereotype.Component;
import org.springframework.transaction.annotation.Transactional;

import com.csc.banking.model.UserAttempts;
@Component
public class UserAttemptsDao 
{
	@PersistenceContext private EntityManager em;
	
	
	public UserAttempts getUserAttempts(String userName)
	{
	try{
		TypedQuery<UserAttempts> query = 
			em.createQuery("SELECT g FROM UserAttempts g where LOWER(g.userName)=:userName",
	            UserAttempts.class)
	            .setParameter("userName", userName.trim().toLowerCase());
	   
		   return query.getSingleResult();
	   }
	   catch(Exception e)
	   {
		
		   return null;
	   }
	    	
	}
	@Transactional
	public void persist(UserAttempts user){
		em.persist(user);
		
	}
	@Transactional
	public void updateAttempts(String user){
		Query q=em.createQuery("UPDATE UserAttempts c SET c.attempts = c.attempts + 1, c.lastModified =:LastModified WHERE c.userName =:user")
		.setParameter("LastModified", new Date())
		.setParameter("user", user);
		q.executeUpdate();
	}
	@Transactional
	public void resetAttempts(String user){
		em.createQuery("UPDATE UserAttempts SET attempts = 0, lastModified = null WHERE userName =:userName")
		.setParameter("userName", user).executeUpdate();
	}
	@Transactional
	public void updateAccountLocked(String user){
		em.createQuery("UPDATE Customer c SET c.isLock =:lock WHERE c.userName =:userName")
		.setParameter("lock", false)
		.setParameter("userName", user).executeUpdate();
	}
	public int isUserExistInCustomer(String user){
		return em.createQuery("SELECT count(c) FROM Customer c WHERE c.userName =:userName").
				setParameter("userName", user).getResultList().size();
	}
}
